package com.yanftch.hdc_tools.insertcode.dialog

import com.intellij.openapi.ui.DialogWrapper
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import com.yanftch.hdc_tools.insertcode.bean.CodeBean
import javax.swing.DefaultListModel
import javax.swing.JComponent
import javax.swing.event.ListSelectionEvent
import javax.swing.event.ListSelectionListener

class CodeDialog (codes: List<CodeBean>) : DialogWrapper(true) {
    private val codeList = JBList<String>()
    private var selectedCode: CodeBean? = null

    init {
        // 将 Code 对象的 name 字段填充到 JList 中
        val codeNames = codes.map { it.name }.toTypedArray()
        codeList.model = DefaultListModel<String>().apply {
            codeNames.forEach { addElement(it) }
        }

        codeList.addListSelectionListener(object : ListSelectionListener {
            override fun valueChanged(e: ListSelectionEvent) {
                if (!e.valueIsAdjusting) {  // 确保只在用户停止选择时触发
                    val selectedIndex = codeList.selectedIndex
                    if (selectedIndex >= 0) {
                        selectedCode = codes[selectedIndex]
                        println("Selected Code: ${selectedCode?.name}, Value: ${selectedCode?.value}")
                    }
                }
            }
        })

        init()
        title = "Select Code"
        setOKButtonText("OK")
        setCancelButtonText("Cancel")
    }

    override fun createCenterPanel(): JComponent? {
        return JBScrollPane(codeList)  // 将 JList 放入 JScrollPane 以支持滚动
    }
}
